import os
import sys
import asyncio
import json
import time
from threading import Thread
from urllib.parse import parse_qs
import random
from PySide6.QtCore import *
from PySide6.QtNetwork import *
from PySide6.QtWebEngineCore import *
from PySide6.QtWebEngineWidgets import *
from PySide6.QtWidgets import *

# import demjson
import mitmproxy.http
import mitmproxy
from mitmproxy import ctx
from mitmproxy.options import Options
from mitmproxy.tools.dump import DumpMaster

from app.unit import S

BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))


class PDDWeb(QWebEngineView):
    drop_down = Signal()

    def __init__(self, user: str = 'default'):
        super().__init__()
        self.user = user
        print(user)
        self._profile = QWebEngineProfile(str(user))
        s = self._profile.settings()
        s.setAttribute(QWebEngineSettings.PluginsEnabled, True)
        s.setAttribute(QWebEngineSettings.DnsPrefetchEnabled, True)
        s.setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)
        s.setAttribute(QWebEngineSettings.LocalContentCanAccessFileUrls, True)
        self._profile.setCachePath(os.path.join(BASE_DIR, 'WebData'))
        self.cookiePath = os.path.join(BASE_DIR, f'WebData/{user}')
        self._profile.setPersistentStoragePath(self.cookiePath)
        self._profile.setHttpCacheType(QWebEngineProfile.DiskHttpCache)
        self._profile.setPersistentCookiesPolicy(QWebEngineProfile.ForcePersistentCookies)
        ua = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Mobile Safari/537.36'
        self._profile.setHttpUserAgent(ua)
        print(self._profile.isOffTheRecord())
        page = QWebEnginePage(self._profile)
        print(page.profile().isOffTheRecord())
        self.setPage(page)
        print(self.page().profile().isOffTheRecord())
        self.drop_down.connect(self._drop_down)
        # self.page().load(QUrl('https://mobile.pinduoduo.com')
        # self.page().load(QUrl('https://mobile.pinduoduo.com/hub_free_trial_goods.html?trial_id=2312140038027'))

    def _drop_down(self):
        """
        操作JS将下拉进度条滑动到底部
        :return:
        """
        self.page().runJavaScript("window.scrollTo(0, document.body.scrollHeight);")

    def _click_try(self):
        js = """
        // 获取页面中所有的div元素
        var divList = document.getElementsByTagName('div');

        // 遍历所有的div元素，查找内容为"免费试用"的标签并进行点击
        for (var i = 0; i < divList.length; i++) {
          if (divList[i].innerText.trim() === '免费试用') {
            divList[i].click();
            break; // 如果找到并点击了目标div，则跳出循环
          }
        }
        """
        self.page().runJavaScript(js)

    def auto_drop_down(self):
        """
        随机2~5秒 下拉到页面底部
        :return:
        """
        while S.auto:
            time.sleep(random.randint(2, 3))
            self.drop_down.emit()

    def on_listen(self):
        server = Thread(target=self.auto_drop_down, daemon=True)
        server.start()

class TryAddon:
    page = 0

    def request(self, flow: mitmproxy.http.HTTPFlow):
        """"""

    def response(self, flow: mitmproxy.http.HTTPFlow):
        if S.监听:
            if "mobile.pinduoduo.com/proxy/api/api/wizard/magi/trial/child/list" in flow.request.pretty_url:
                result: dict = flow.response.json()
                if "offset=20&count=20" in flow.request.pretty_url:
                    if self.page == 0:
                        self.page = 1
                        print('准备重放')
                        try:
                            # 创建修改后的请求副本并进行重放
                            new_flow = flow.copy()
                            new_url = new_flow.request.url.replace("offset=20&count=20", "offset=0&count=20")
                            new_flow.request.url = new_url
                            ctx.master.commands.call("replay.client", [new_flow])
                            print('重放请求')
                        except Exception as e:
                            print('重放错误：', e)

                if 'offset=' in flow.request.pretty_url:
                    items = result['trial_list']
                    try:
                        for item in items:
                            print(item)
                            tid = item['trial_id']
                            name = item['tiny_name']
                            price = item['price']
                            total = item['inventory']
                            person = item['joiner_count']
                            p = total / person * 100
                            per = "{:.2f}".format(p)
                            pic = item['img']
                            S.item.emit([tid, name, price/100, total, person, eval(per), pic])
                    except Exception as e:
                        print('解析错误', e)

